//
//  ImportWallet.swift
//  Monujo
//
//  Created by user on 2024/1/2.
//

import Foundation

import SwiftUI

struct ImportWalletView: View {
    
    @State private var selectedChain = "Ethereum"
    @State private var address: String = ""
    @State private var isAddressValid: Bool = false
    
    var body: some View {
        NavigationView {
            VStack{
                Text("Select Crypto Chain")
                Picker("Select Crypto Chain", selection: $selectedChain) {
                    Text("Ethereum").tag("Ethereum")
                    Text("Binance Smart Chain").tag("BSC")
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
                
                TextField("Input Public Address", text: $address)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                
                // 显示错误消息
                if !isAddressValid {
                    Text("Invalid address. Please enter a valid address.")
                        .foregroundColor(.red)
                }
                
                
                Button(action: {
                    // validate address after click import wallet
                    validateAndNavigate()
                }, label: {
                    Text("Add Address")
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .padding()
                        .background(Color.blue)
                        .cornerRadius(10)
                }).padding()
                Spacer()
            }
            .navigationBarTitleDisplayMode(.inline)
            .fullScreenCover(isPresented: $isAddressValid) {
                    AssetView(walletAddress: address)
                }
        }
    }
    
    
    
    private func validateAndNavigate() {
        let isValid = EthereumChain().isValidEthereumAddress(address)
        if (isValid) {
            address = EthereumChain().eip55ChecksumAddress(address)
        }
        isAddressValid = isValid
    }
}

struct ImportWalletView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView(content: {
            ImportWalletView()
        })
    }
}
